package threadPoolDemo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.log4j.Logger;

import java.util.concurrent.*;

/**
 * @author Ajie
 * @date 7/16/21
 * @function
 * 当执行拒绝策略时候，怎么办？
 *
 * 结论：添加任务的所在线程 抛出异常（可以捕获）。线程池 正常运行，后续可已继续执行任务。
 * isTerminated:false isShutDown:false
 *
 *
 */
public class AbortPolicyDemo {
    private static final Logger logger = Logger.getLogger(AbortPolicyDemo.class);

    public static void main(String[] args) {
        ThreadFactory guavaThreadFactory = new ThreadFactoryBuilder().setNameFormat("guava-pool-%d").build();

        ExecutorService executorService = new ThreadPoolExecutor(1, 2,
                200L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(2), guavaThreadFactory);

        //让任务 操过最大 容量
        for (int i = 1; i < 10; i++) {//超过了最大值 任务7时，抛出异常 max thread 2+ queue +5.
            try {
                logger.info("customerThreadPool: execute start: " + i);
                int finalI = i;
                executorService.execute(() -> {
                    try {
                        logger.info("customerThreadPool:execute task ing-----> " + finalI + "  " + Thread.currentThread().getName());
                        Thread.sleep(1);
                        logger.info("customerThreadPool:execute task over " + finalI + Thread.currentThread().getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                logger.info("Reject Exception thread:》》》 " + Thread.currentThread().getName());
                e.printStackTrace();
            }
        }

        //TODO  拒绝策略后的线程池 执行情况：
        try {
            TimeUnit.SECONDS.sleep(4);
            logger.info("customerThreadPool:Reject after---- last task before 》》》 " + Thread.currentThread().getName());
            logger.info("main: last task》》》》isTerminated:" + executorService.isTerminated() + " isShutDown:" + executorService.isShutdown());
            executorService.submit(() -> {
                logger.info("customerThreadPool:last task 》》》" + Thread.currentThread().getName());
            });

            for (int i = 0; i < 5; i++) {
                int finalI = i;
                executorService.execute(() -> {
                    logger.info("customerThreadPool:last task 》》》after---> " + finalI + "  " + Thread.currentThread().getName());
                });
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
